﻿using Newtonsoft.Json;
using System;

namespace Blog.IdentityServer.Helper
{
    /// <summary>
    /// 自定义布尔类型数据转换规则
    /// </summary>
    public class BoolConverter : JsonConverter
    {
        private const string TrueStr = "1";
        private const string FalseStr = "0";
        public override bool CanConvert(Type objectType) => true;

        //反序列化
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.ValueType == typeof(string))
            {
                if ((string)reader.Value == TrueStr)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        //序列化
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value.GetType() == typeof(bool))
            {
                bool result = (bool)value;
                if (result)
                {
                    writer.WriteValue(TrueStr);
                }
                else
                {
                    writer.WriteValue(FalseStr);
                }
            }
        }
    }

}
